import React from 'react';
import createLoading from 'dva-loading';
import dva from 'dva';
import { Router, Route } from 'dva/router';
// import createHistory from 'history/createBrowserHistory';
import 'ywen-mobile-ui/assets/styles/index.less';
import 'antd-mobile/lib/date-picker/style/css';
import '../../assets/styles/app.less';
import { DEBUG } from '../../common/constants/setting';
import App from '../../common/routes/index';

import GlobalModel from '../../common/models/global';
import OilStationModel from '../../common/models/oilStation';
import PayModel from '../../common/models/pay';
import CouponModel from '../../common/models/coupon';
import UserModel from '../../common/models/user';
import RefuelModel from '../../common/models/refuel';
import InsuranceModel from '../../common/models/insurance';
import EscortModel from '../../common/models/escort';
import CodeModel from '../../common/models/code';
import CardModel from '../../common/models/card';
import InvoiceModel from '../../common/models/invoice';
import VipModel from '../../common/models/vip';

let app;


export function init() {
  const options = {
    onError(e) {
      console.error(e);
    },
  };

  if (DEBUG) {
    const { createLogger } = require('redux-logger');
    // redux-logger
    const logMiddleware = createLogger({
      duration: true,
      level: 'log',
      logger: console,
      // 打印immutablejs的state
      stateTransformer: (state) => {
        const result = {};
        Object.keys(state).forEach((key) => {
          if (state[key].toJS) {
            result[key] = state[key].toJS();
          } else {
            result[key] = state[key];
          }
        });
        return result;
      },
    });

    options.onAction = logMiddleware;
  }

  app = dva(options);
  app.model(GlobalModel);
  app.model(OilStationModel);
  app.model(PayModel);
  app.model(CouponModel);
  app.model(UserModel);
  app.model(RefuelModel);
  app.model(InsuranceModel);
  app.model(EscortModel);
  app.model(CodeModel);
  app.model(CardModel);
  app.model(InvoiceModel);
  app.model(VipModel);
  app.use(createLoading());
  app.router(({ history }) => {
    return (
      <Router history={history}>
        <Route path="/" component={App} />
      </Router>
    );
  });
  return app.start('#app');
}

export function getStore() {
  return app._store;
}

export function getApp() {
  return app;
}

export function getHistory() {
  return app._history;
}
